import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'

import NavBar from '@/components/layouts/NavBar'
import Bind from '@/components/onboard/Bind'
import SignUp from '@/components/onboard/SignUp'
import { createClient } from '@/utils/supabase/server'

import { UserProvider } from './user-provider'

export default async function OnboardLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const supabase = createClient()

  const cookieStore = cookies()
  const token = cookieStore.get('token')
  const { data: user, error } = await supabase
    .from('user')
    .select()
    .eq('id', token?.value)
    .single()

  if (error) {
    console.log('getUser error', error)
    return redirect('/login')
  }
  console.log('data', user)

  const Component = () => {
    if (user.status === 0) {
      return <SignUp id={user.id} />
    }

    if (user.status === 1) {
      return <Bind id={user.id} />
    }

    return children
  }

  return (
    <main className="min-h-screen flex flex-col">
      <NavBar user={user} />
      <UserProvider value={user}>
        <div className="container">{Component()}</div>
      </UserProvider>
    </main>
  )
}
